﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Sherwood.SignOn.Server.Models;
using Sherwood.SignOn.Server.Models.ViewModels;
using Sherwood.Mvc.Localization;
using Sherwood.Mvc;
using log4net;
using Sherwood.SignOn.Server.Models.Services;
using Sherwood.SignOn.Server.Content;
using Sherwood.SignOn.Server.Models.Repositories;

namespace Sherwood.SignOn.Server.Controllers
{
    /// <summary>
    /// Controller for SignIn requests
    /// </summary>
    public class SignInController : ControllerBase
    {

        private static readonly ILog Log = LogManager.GetLogger(typeof(SignInController));


        /// <summary>
        /// /SignIn/ action.
        /// The purpose of this action is to allow users to sign in using a username and password.
        /// If a session already exists for a user, the user is auto-authenticated (login page is never actually displayed).
        /// The action also records sign-out URLs as provided in the request.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ValidateInput(false)]    
        public ActionResult Index(SignInViewModel model)
        {
            //Default value for "Remember Me" should be set to what the user previously selected if user is logged in.
            if (Request.HttpMethod.ToLower() == "get")
            {
                IUserSession currentSession = UserSessionHelper.GetCurrentUserSession();
                if (currentSession != null)
                {
                    model.RememberMe = currentSession.Persistent.GetValueOrDefault(false);
                }
            }

            //Read / write cookie, just to check if cookies are enabled.
            bool cookiesSupported = true;
            if (Request != null)
            {
                HttpCookie requestTestCookie = Request.Cookies["CookiesEnabled"];
                cookiesSupported = requestTestCookie != null && requestTestCookie.Value != null && requestTestCookie.Value.Equals("True");
            }
            if (Response != null)
            {
                HttpCookie responseTestCookie = new HttpCookie("CookiesEnabled");
                responseTestCookie.Value = "True";
                Response.SetCookie(responseTestCookie);
            }

            //End user session if no username / password is provided.
            //In effect, this will mean that visiting the login page will sign the user out.
            if (string.IsNullOrEmpty(model.UserName) && string.IsNullOrEmpty(model.Password) && string.IsNullOrEmpty(model.ReturnUrl))
                UserSessionHelper.EndCurrentUserSession();


            //Authenticate user
            bool userAuthenticated = model.AuthenticateUser(ModelState);
            if (userAuthenticated)
            {
                if (!cookiesSupported)
                {
                    if (!model.TestCookieWritten) //Redirect to self (to allow cookie to be read)
                    {
                        string testCookieUrl = this.Request.Url.AbsoluteUri;
                        if (testCookieUrl.Contains("?"))
                            testCookieUrl = testCookieUrl + "&TestCookieWritten=true";
                        else
                            testCookieUrl = testCookieUrl + "?TestCookieWritten=true";
                        return Redirect(testCookieUrl);
                    }
                    else
                    {
                        bool requireLogin = true;
                        if (!string.IsNullOrEmpty(model.RequireLogin))
                            bool.TryParse(model.RequireLogin, out requireLogin);
                        if (requireLogin) //If the url requested by the user required login (i.e. expects the login page to be displayed)
                        {
                            return View("NoCookies", model);
                        }
                        else //if a login page should not be shown for the originally requested url
                        {
                            return Content(Translations.NoCookies_Message); //return a simpler message
                        }
                    }
                }
                else
                {
                    //Redirect to application
                    IUserSession currentSession = UserSessionHelper.GetCurrentUserSession();
                    return Redirect(model.GetParameterizedReturnUrl(currentSession));
                }
            }
            if (!string.IsNullOrEmpty(model.ReturnUrl) && Response != null)
            {
                Response.StatusCode = 403;
                Response.StatusDescription = "Authentication required";
            }
            return View(model);
        }



        public ActionResult SignInSuccess()
        {
            return View();
        }
    }
}
